package com.aspirecn.auth.service;

import com.aspirecn.auth.domain.SysUser;
import com.aspirecn.auth.domain.vo.ResponseHead;
import com.aspirecn.auth.domain.vo.ResponseMsg;
import com.aspirecn.auth.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SysUserServiceImpl implements ISysUserService {

  @Autowired
  private SysUserRepository sysUserRepository;
  @Autowired
  private UserDetailsService userDetailsService;
  @Override
  public ResponseMsg updaterUserPwd(String newPwd, String userName,
                                    String oldPwd) {
    if (newPwd == null || oldPwd == null || newPwd.length() == 0 || oldPwd.length() == 0) {
      throw new RuntimeException("密码不能为空!");
    }
    if (newPwd.length() < 8) {
      throw new RuntimeException("密码长度不能小于8!");
    }
    UserDetails sysUser = userDetailsService.loadUserByUsername(userName);
     PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
     ResponseMsg responseMsg = new ResponseMsg<>();
    responseMsg.setData(null);
    final ResponseHead head = new ResponseHead();
    if (sysUser != null) {
      final boolean checkpw = BCrypt.checkpw(oldPwd, sysUser.getPassword());
      if (!checkpw) {
        head.setRequestId("1");
        head.setRespCode("01");
        head.setRespStatus("01");
        head.setRespDesc("修改密码失败！");
        responseMsg.setHead(head);
        return responseMsg;
      }

      newPwd = passwordEncoder.encode(newPwd);
      sysUserRepository.updatePwd(newPwd, sysUser.getUsername());
      head.setRespCode("00");
      head.setRespStatus("00");
      head.setRequestId("1");
      head.setRespDesc("修改密码成功!");
      responseMsg.setHead(head);
      return responseMsg;
    }
    head.setRequestId("1");
    head.setRespCode("01");
    head.setRespStatus("01");
    head.setRespDesc("修改密码失败！");
    responseMsg.setHead(head);
    return responseMsg;
  }
  @Override
  public SysUser findOneByUserName(String username) {
    return sysUserRepository.findOneByUserName(username);
  }
}
